package my.jieh.tips.swing;

import java.awt.*;
import javax.swing.*;

public class ListLeaders {
  static class MyCellRenderer
      extends JPanel
      implements ListCellRenderer {
    JLabel left;
    JLabel right;
    MyCellRenderer() {
      setLayout(new GridLayout(1, 2));
      left = new JLabel();
      right = new JLabel();
      left.setOpaque(true);
      right.setOpaque(true);
      add(left);
      add(right);
    }

    public Component getListCellRendererComponent(
        JList list,
        Object value,
        int index,
        boolean isSelected,
        boolean cellHasFocus) {
      String leftData = ( (String[]) value)[0];
      String rightData = ( (String[]) value)[1];
      left.setText(leftData);
      right.setText(rightData);
      if (isSelected) {
        right.setBackground(
            list.getSelectionBackground());
        right.setForeground(
            list.getSelectionForeground());
        left.setBackground(
            list.getSelectionBackground());
        left.setForeground(
            list.getSelectionForeground());
      }
      else {
        right.setBackground(list.getBackground());
        right.setForeground(list.getForeground());
        left.setBackground(list.getBackground());
        left.setForeground(list.getForeground());
      }
      setEnabled(list.isEnabled());
      setFont(list.getFont());
      return this;
    }
  }

  public static void main(String args[]) {
    JFrame frame = new JFrame("ListLeaders");
    frame.setDefaultCloseOperation(
        JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();
    String data[][] = {
        {
        "Tony Blair", "England"}
        , {
        "Thabo Mbeki", "South Africa"}
        , {
        "Megawati Soekarnoputri", "Indonesia"}
        , {
        "Hosni Mubarak", "Egypt"}
        , {
        "Vladimir Putin", "Russia"}
        , {
        "Vicente Fox", "Mexico"}
        , {
        "Ariel Sharon", "Israel"}
    };
    JList list = new JList(data);
    list.setCellRenderer(new MyCellRenderer());
    JScrollPane scrollPane = new JScrollPane(list);
    contentPane.add(scrollPane, BorderLayout.CENTER);
    frame.setSize(300, 150);
    frame.show();
  }
}